<template>
   <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <div class="structure_cent_b">
          <div class="structure_cent_b_left">
            <a-tree
              :tree-data="bumentreeData"
              :replaceFields='replaceFields'
              @select='clicktree'
              :default-selected-keys="defaultselected"
            ></a-tree>
          </div>
          <div class="structure_cent_b_right">
            <div class="structure_cent_b_title">
              <a-button
                type='primary'
                 v-action:add
                @click="adddepartment1"
              >新增</a-button>
              <a-button
               v-action:edit
                type='danger'
                style="margin-left:20px;"
                @click="bianji"
              >编辑</a-button>
              <a-button
               v-action:refresh
                type='primary'
                style="margin-left:20px;"
                @click="getbumenTree"
              >刷新</a-button>

            </div>
       
          <a-table
            :columns="columns"
            :data-source="datalist"
            bordered
            :rowKey='record=>record.id'
            :pagination="false"
            :childrenColumnName="'childList'"
          >
            <template
              slot="type"
              slot-scope="text"
            >
              {{yingjilist[text].name}}
            </template>
            <template
              slot="操作"
              slot-scope="text, record"
            >-
              <a-popconfirm
                style="margin-left:20px"
                cancelText='取消'
                okText="确认"
                title="您确定要删除吗?"
                @confirm="onDelete(record)"
              >
                <a  v-action:del href="javascript:;">删除</a>
              </a-popconfirm>
            </template>

          </a-table>
   </div>
        </div>
      </div>
      <!-- 新增 -->
      <a-modal
        :title="usertitle"
        :visible="visible1"
        :confirm-loading="confirmLoading1"
        @ok="tijiaobumen"
        @cancel="handleCancel"
        :destroyOnClose='true'
        cancel-text="取消"
        ok-text="确定"
      >
        <a-form
          :form="bumenform"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
          @submit="tijiaobumen"
        >
          <a-form-item label="新增类型">
            <a-select
              v-model="typeId"
              placeholder="请选择新增类型"
            >
              <a-select-option
                v-for="(item,i) in yingjilist"
                :key="i"
                :value="item.id"
              >{{item.name}}</a-select-option>

            </a-select>
          </a-form-item>
          <a-form-item
            label="公司全称"
            v-if="typeId==0"
          >
            <a-input
              placeholder="请输入公司全称"
              v-decorator="['fullName', { rules: [{ required: true, message: '请输入公司全称' }] }]"
            />
          </a-form-item>
          <a-form-item
            label="公司简称"
            v-if="typeId==0"
          >
            <a-input
              placeholder="请输入公司简称"
              v-decorator="['name', { rules: [{ required: true, message: '请输入公司简称' }] }]"
            />
          </a-form-item>
          <a-form-item
            label="选择上级"
            v-if="typeId==0"
          >
            <a-tree-select
              v-decorator="[
                    'parentId',
                    { rules: [{ required: false, message: '请选择上级' }] },
                  ]"
              style="width: 100%"
              :tree-data="treeData"
              placeholder="请选择上级"
              :show-checked-strategy="SHOW_PARENT"
              :replaceFields='replaceFields'
              @change='selectgongsitree'
            />
          </a-form-item>
          <a-form-item
            label="部门名称"
            v-if="typeId==1"
          >
            <a-input
              placeholder="请输入部门名称"
              v-decorator="['bumenname', { rules: [{ required: true, message: '请输入部门名称' }] }]"
            />
          </a-form-item>
          <a-form-item
            label="选择上级"
            v-if="typeId==1"
          >
            <a-tree-select
              v-decorator="[
                    'bumenparentId',
                    { rules: [{ required: true, message: '请选择上级' }] },
                  ]"
              style="width: 100%"
              placeholder="请选择上级"
              :tree-data="bumentreeData"
              :show-checked-strategy="SHOW_PARENT"
              :replaceFields='replaceFields'
              @change='selecttree'
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>

   </page-header-wrapper>
</template>

<script>
import {
  getTree,
  adddepartment,
  addgongsi,
  gongsiTree,
  getgongsi,
  getbumen,
  deletebumen,
  deletegongsi,
} from "@/api/structure";
import { TreeSelect } from "ant-design-vue";
import { getTreeData, getchild } from "@/utils/util";

const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const columns = [
  {
    title: "名称",
    dataIndex: "name",
    align: "center",
  },
  {
    title: "类型",
    dataIndex: "type",
    align: "center",
    scopedSlots: { customRender: "type" },
  },
  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: { customRender: "操作" },
    align: "center",
  },
];
export default {
  data() {
    return {
      SHOW_PARENT,
      confirmLoading1: false,
      visible1: false,
      replaceFields: {
        children: "childList",
        title: "name",
        key: "id",
        value: "id",
      },
      usertitle: "",
      datalist: [],
      treeData: [],
      bumentreeData: [],
      bianjitype: 0,
      columns,
      bianjiId: "",
      defaultselected: [],
      shu: "",
      form: this.$form.createForm(this, { name: "coordinated" }),
      bumenform: this.$form.createForm(this, { name: "coordinated1" }),
      userarr: [],
      typeId: 0,
      bumenarr: "",
      xuanzhongarr: [],
      yingjilist: [
        { id: 0, name: "公司" },
        { id: 1, name: "部门" },
      ],
    };
  },
  mounted() {
    this.getgongsiTree();
    this.getbumenTree();
  },
  methods: {
    //获取公司树
    getgongsiTree() {
      new Promise((resolve, reject) => {
        gongsiTree()
          .then((response) => {
            console.log(response);
            if (response.code == 0) {
              this.treeData = response.data;
              this.datalist = this.treeData;
              this.defaultselected = [];
              // this.defaultselected=this.treeData[0].id
              this.defaultselected.push(this.treeData[0].id);
              console.log(this.defaultselected);
            } else {
              this.$notification.error({
                message: "失败",
                description: response.msg,
              });
            }
            resolve();
          })
          .catch((error) => {
            // this.$notification.error({
            //   message: "失败",
            //   description: `获取失败`,
            // });
            reject(error);
          });
      });
    },
    //获取公司部门树
    getbumenTree() {
      new Promise((resolve, reject) => {
        getTree()
          .then((response) => {
            console.log(response);
            if (response.code == 0) {
              this.bumentreeData = response.data;
              this.defaultselected = [];
              // this.defaultselected.push(
              //   this.bumentreeData[0].id
              // )
              // console.log(this.defaultselected);
              this.clicktree(this.defaultselected);
            } else {
              this.$notification.error({
                message: "失败",
                description: response.msg,
              });
            }
            resolve();
          })
          .catch((error) => {
            // this.$notification.error({
            //   message: "失败",
            //   description: `获取失败`,
            // });
            reject(error);
          });
      });
    },
    //点击人组织架构树
    clicktree(val, e) {
      console.log(this.shu);
      console.log("值", val);
      if (val.length) {
        this.defaultselected = [];
        this.defaultselected.push(val[0]);
        this.xuanzhongarr = getTreeData(
          this.defaultselected,
          this.bumentreeData
        );
        this.datalist = this.xuanzhongarr[0].childList;
        console.log(this.xuanzhongarr);
        console.log(this.defaultselected);
      } else {
        this.datalist = this.bumentreeData;
        this.xuanzhongarr = [];
      }
    },
    //删除
    onDelete(val) {
      if (val.type == 0) {
        new Promise((resolve, reject) => {
          deletegongsi({ id: val.id })
            .then((response) => {
              if (response.code == 0) {
                this.getbumenTree();
                this.$notification.success({
                  message: "成功",
                  description: "删除成功",
                });
              } else {
                this.$notification.error({
                  message: "失败",
                  description: response.msg,
                });
              }
              resolve();
            })
            .catch((error) => {
              this.$notification.error({
                message: "失败",
                description: `查询失败`,
              });
              reject(error);
            });
        });
      } else if (val.type == 1) {
        new Promise((resolve, reject) => {
          deletebumen({ id: val.id })
            .then((response) => {
              if (response.code == 0) {
                this.getbumenTree();
                this.$notification.success({
                  message: "成功",
                  description: "删除成功",
                });
              } else {
                this.$notification.error({
                  message: "失败",
                  description: response.msg,
                });
              }
              resolve();
            })
            .catch((error) => {
              this.$notification.error({
                message: "失败",
                description: `查询失败`,
              });
              reject(error);
            });
        });
      }
    },
    //编辑
    bianji() {
      this.bianjitype = 1;
      this.usertitle = "编辑";

      if (this.xuanzhongarr.length) {
        this.typeId = this.xuanzhongarr[0].type;
        this.bianjiId = this.xuanzhongarr[0].id;
        if (this.typeId == 0) {
          //公司
          new Promise((resolve, reject) => {
            getgongsi({ id: this.bianjiId })
              .then((response) => {
                if (response.code == 0) {
                  this.visible1 = true;
                  console.log(response);
                  this.$nextTick(() => {
                    this.bumenform.setFieldsValue({
                      fullName: response.data.fullName,
                      name: response.data.name,
                      parentId:
                        response.data.parentId == 0
                          ? ""
                          : response.data.parentId,
                    });
                  });
                } else {
                  this.$notification.error({
                    message: "失败",
                    description: response.msg,
                  });
                }
                resolve();
              })
              .catch((error) => {
                this.$notification.error({
                  message: "失败",
                  description: `查询失败`,
                });
                reject(error);
              });
          });
        } else if (this.typeId == 1) {
          //部门
          new Promise((resolve, reject) => {
            getbumen({ id: this.bianjiId })
              .then((response) => {
                if (response.code == 0) {
                  this.visible1 = true;
                  console.log(response);
                  this.$nextTick(() => {
                    this.bumenform.setFieldsValue({
                      bumenname: response.data.name,
                      bumenparentId: response.data.compId,
                    });
                  });
                } else {
                  this.$notification.error({
                    message: "失败",
                    description: response.msg,
                  });
                }
                resolve();
              })
              .catch((error) => {
                this.$notification.error({
                  message: "失败",
                  description: `查询失败`,
                });
                reject(error);
              });
          });
        }
      } else {
        this.$notification.error({
          message: "失败",
          description: `请选择数据`,
        });
      }
    },
    //选择人员树
    selectusertree(value, label, extra) {
      console.log("人员", value, label, extra);
      this.userarr = [];
      let userid = [];
      if (value.length != 0) {
        value.forEach((item) => {
          userid.push(item.value);
        });
        this.userarr = getTreeData(userid, this.treeData);
      }
      console.log(this.userarr);
    },

    //新增部门
    adddepartment1() {
      this.usertitle = "新增";
      this.visible1 = true;
      this.bianjitype = 0;
    },
    //选择部门树
    selecttree(value, label, extra) {
      this.bumenarr = "";
      let arr = [];
      arr.push(value);
      console.log("部门", value);
      console.log("部门", arr);
      this.bumenarr = getTreeData(arr, this.bumentreeData);
      console.log(this.bumenarr);
    },
    //选择公司树
    selectgongsitree(value, label, extra) {
      this.bumenarr = "";
      let arr = [];
      arr.push(value);
      console.log("公司", value);
      console.log("公司", arr);
      this.bumenarr = getTreeData(arr, this.treeData);
      console.log(this.bumenarr);
    },
    //提交新增
    tijiaobumen(e) {
      e.preventDefault();
      this.bumenform.validateFields((err, values) => {
        if (!err) {
          console.log("新增", values);
          this.confirmLoading1 = true;
          if (this.typeId == 0) {
            //新增公司
            if (this.bianjitype == 0) {
              new Promise((resolve, reject) => {
                addgongsi(values)
                  .then((response) => {
                    if (response.code == 0) {
                      this.confirmLoading1 = false;
                      this.getbumenTree();
                      this.$notification.success({
                        message: "成功",
                        description: "提交成功",
                      });
                      this.visible1 = false;
                    } else {
                      this.confirmLoading1 = false;
                      this.$notification.error({
                        message: "失败",
                        description: response.msg,
                      });
                    }
                    resolve();
                  })
                  .catch((error) => {
                    this.confirmLoading1 = false;
                    this.$notification.error({
                      message: "失败",
                      description: `提交失败`,
                    });
                    reject(error);
                  });
              });
            } else {
              let data = {
                fullName: values.fullName,
                name: values.name,
                parentId: values.parentId,
                id: this.bianjiId,
              };
              new Promise((resolve, reject) => {
                addgongsi(data)
                  .then((response) => {
                    if (response.code == 0) {
                      this.confirmLoading1 = false;
                      this.getbumenTree();
                      this.$notification.success({
                        message: "成功",
                        description: "提交成功",
                      });
                      this.visible1 = false;
                    } else {
                      this.confirmLoading1 = false;
                      this.$notification.error({
                        message: "失败",
                        description: response.msg,
                      });
                    }
                    resolve();
                  })
                  .catch((error) => {
                    this.confirmLoading1 = false;
                    this.$notification.error({
                      message: "失败",
                      description: `提交失败`,
                    });
                    reject(error);
                  });
              });
            }
          } else if (this.typeId == 1) {
            //新增部门
            if (this.bianjitype == 0) {
              let data = {
                name: values.bumenname,
                parentId: values.bumenparentId,
                parentIdType: this.bumenarr[0].type,
              };
              new Promise((resolve, reject) => {
                adddepartment(data)
                  .then((response) => {
                    if (response.code == 0) {
                      this.confirmLoading1 = false;
                      this.getbumenTree();
                      this.$notification.success({
                        message: "成功",
                        description: "提交成功",
                      });
                      this.visible1 = false;
                    } else {
                      this.confirmLoading1 = false;
                      this.$notification.error({
                        message: "失败",
                        description: response.msg,
                      });
                    }
                    resolve();
                  })
                  .catch((error) => {
                    this.confirmLoading1 = false;
                    this.$notification.error({
                      message: "失败",
                      description: `提交失败`,
                    });
                    reject(error);
                  });
              });
            } else {
              let data = {
                name: values.bumenname,
                parentId: values.bumenparentId,
                parentIdType: this.bumenarr[0].type,
                id: this.bianjiId,
              };
              new Promise((resolve, reject) => {
                adddepartment(data)
                  .then((response) => {
                    if (response.code == 0) {
                      this.confirmLoading1 = false;
                      this.getbumenTree();
                      this.$notification.success({
                        message: "成功",
                        description: "提交成功",
                      });
                      this.visible1 = false;
                    } else {
                      this.confirmLoading1 = false;
                      this.$notification.error({
                        message: "失败",
                        description: response.msg,
                      });
                    }
                    resolve();
                  })
                  .catch((error) => {
                    this.confirmLoading1 = false;
                    this.$notification.error({
                      message: "失败",
                      description: `提交失败`,
                    });
                    reject(error);
                  });
              });
            }
            console.log("部门", values);
          }
        }
      });
    },
    //取消弹窗
    handleCancel(e) {
      this.confirmLoading1 = false;
      this.visible1 = false;
    },
  },
};
</script>

<style scoped>
.structure_cent{
  background: #fff;
  border: 1px solid #ccc;
}
.structure_cent_title{
  width: 100%;
  font-size: 16px;
  color: #333;
  background: #f6f6f6;
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  border-bottom: 1px solid #ccc;
}
.structure_cent_title span{
  border-left: 4px solid #0086ff;
  padding-left: 15px;
}
.structure_cent_b{
  max-width: 1200px;
  margin: auto;
  padding-bottom: 60px;
  display: flex;
  justify-content: space-between;
}
.structure_cent_b_left{
  width: 300px;
  border: 1px solid #ccc;
}
.structure_cent_b_right{
  width: 800px;
  margin-left: 20px;
}
.structure_cent_b_title{
  margin-bottom: 30px;
}
.addbtn_f{
  width: 400px;
  display: flex;
  justify-content: space-between;
}
.addbtn_f div{
  width: 100px;
  height: 35px;
  border: 1px solid #ccc;
  text-align: center;
  line-height: 35px;
  font-size: 13px;
  color: #333;
  cursor: pointer;
  background: #f2f2f2;
}

.addbtn_f div:hover{
  background: #0086ff;
  color: #fff;
}
</style>